package com.data.util;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;


/**
 * 文件续传
 *
 * @author:HingLo
 * @create 2017-08-24 14:11
 **/
public class FileResumeUtils {
    private static Logger logger = Logger.getLogger(FileResumeUtils.class);

    /**
     * 定义文件存放的位置
     *
     * @return
     */
    public static String rootPath() {
        String os = System.getProperty("os.name");
        if (os.toLowerCase().startsWith("win")) {
            return "E:/root/";
        } else {
            return "/root/";
        }
    }


    /**
     * 复制文件到临时文件中
     *
     * @param path
     * @param inputStream
     * @return
     */
    public static boolean uploadFile(String path, CommonsMultipartFile inputStream) {
        try {
            FileUtils.copyInputStreamToFile(inputStream.getInputStream(), new File(path));
            return true;
        } catch (IOException e) {
            return false;
        }


    }

    /**
     * 复制apk到真正的文件中去
     *
     * @param id session id,用于读取临时文件中的apk
     * @return 返回一个文件的md5 值，文件的的md5值就是文件的名称
     */
    public static boolean readUploadTempFileUtils(String id, String md5) {
        StringBuilder rpath = new StringBuilder(FinalStringUtils.TEMPATH).append("apk/");//临时文件的路径
        StringBuilder wPath = new StringBuilder(FinalStringUtils.APKPATH).append("apk/");//文件保存的路径
        StringBuilder path = new StringBuilder(rpath.toString()).append(id).append(".apk");
        File file = new File(path.toString());
        try {
            if (file.exists() && file.isFile()) {//apk文件是否存在
                //复制apk到真正文件储存的地方去
                FileUtils.copyFile(file, new File(wPath.append(md5).append(".apk").toString()));
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        deleteFile(path.toString());
        return false;
    }

    /***
     * 删除文件
     * @param path
     * @return
     */
    public static boolean deleteFile(String path) {
        logger.debug(path);
        File file = new File(path);
        if (file.exists() && file.isFile()) {
            return file.delete();
        }
        return false;
    }

    /***
     * 删除目录
     * @param path
     * @return
     */
    public static boolean deleteDir(String path) {
        File dir = new File(path);
        if (dir.exists() && dir.isDirectory()) {
            File[] tmp = dir.listFiles();
            for (int i = 0; i < tmp.length; i++) {
                if (tmp[i].isDirectory()) {
                    deleteDir(path + "/" + tmp[i].getName());
                } else {
                    tmp[i].delete();
                }
            }
            return dir.delete();
        }
        return false;
    }

    /**
     * 将应用个截图复制到真正的文件下
     *
     * @param name
     * @param rid
     * @param sid
     * @return
     */
    public static boolean copyIcon(String name[], String rid, String sid) {
        String path = FinalStringUtils.TEMPATH + "image/" + sid + "/";//临时文件的路径
        String wpath = FinalStringUtils.IMAGEPATH + rid + "/";//软件新的路径

        try {
            for (String s : name) {

                String s1 = path + s;
                String s2 = wpath + s;
                FileUtils.copyFile(new File(s1), new File(s2));
            }
            deleteDir(path);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;

    }

    /**
     * 保存图标操作
     *
     * @param file
     * @param rid
     * @return
     */
    public static String saveMinIcon(CommonsMultipartFile file, String rid) {
        String wpath = FinalStringUtils.IMAGEPATH + rid + "/";//软件新的路径
        String filename = file.getOriginalFilename();
        String s = filename.substring(filename.lastIndexOf("."));//获取文件的后缀
        String newFile = DatabaseIdUtils.getDataIdOne() + s;

        try {

            FileUtils.copyInputStreamToFile(file.getInputStream(), new File(wpath + newFile));
            return newFile;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 读取图片
     *
     * @param rid
     * @param iconName
     * @return
     */
    public static byte[] readMinIcon(String rid, String iconName) {
        String wpath = FinalStringUtils.IMAGEPATH + rid + "/" + iconName;//软件新的路径
        File file = new File(wpath);
        try {
            return FileUtils.readFileToByteArray(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 软件下载
     *
     * @param fileName 文件名称
     * @param filePath 文件路径
     * @param request
     * @param response
     * @throws IOException
     */

    public static void downloadApk(String fileName, String filePath, HttpServletRequest request, HttpServletResponse response) throws IOException {
        File proposeFile = new File(filePath);
        long fSize = proposeFile.length();
        // 下载
        response.setContentType("application/x-download");
        String isoFileName = fileName;
        response.setHeader("Accept-Ranges", "bytes");
        response.setHeader("Content-Length", String.valueOf(fSize));
        response.setHeader("Content-Disposition", "attachment; filename="
                + isoFileName);
        long pos = 0;
        if (null != request.getHeader("Range")) {
            // 断点续传
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
            try {
                pos = Long.parseLong(request.getHeader("Range").replaceAll(
                        "bytes=", "").replaceAll("-", ""));
                response.setHeader("Content-Length", String.valueOf(fSize - pos));
            } catch (NumberFormatException e) {
                pos = 0;
            }
        }
        ServletOutputStream out = response.getOutputStream();
        BufferedOutputStream bufferOut = new BufferedOutputStream(out);
        InputStream inputStream = new FileInputStream(proposeFile);
        String contentRange = new StringBuffer("bytes ").append(
                new Long(pos).toString()).append("-").append(
                new Long(fSize - 1).toString()).append("/").append(
                new Long(fSize).toString()).toString();
        response.setHeader("Content-Range", contentRange);
        inputStream.skip(pos);
        byte[] buffer = new byte[5 * 1024];
        int length;
        while ((length = inputStream.read(buffer, 0, buffer.length)) != -1) {
            bufferOut.write(buffer, 0, length);
        }
        bufferOut.flush();
        bufferOut.close();
        out.close();
        inputStream.close();
    }

    public static String saveFindImageUtils(CommonsMultipartFile file, String filname, int type) {
        String path = FinalStringUtils.FINDPATH + "image/";
        try {
            String id = DatabaseIdUtils.getDataIdOne() + filname;
            FileUtils.copyInputStreamToFile(file.getInputStream(), new File(path + id));
            return id;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 读取图片
     *
     * @param id
     * @return
     */
    public static byte[] readFindIcon(String id) {
        String wpath = FinalStringUtils.FINDPATH + "image/" + id;
        File file = new File(wpath);
        try {
            return FileUtils.readFileToByteArray(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        System.out.println(rootPath());
    }
}
